package com.zhehekeji.opsys.api.service.manager;

import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.math.NumberUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import com.zhehekeji.opsys.api.cache.OperationCache;
import com.zhehekeji.opsys.api.cache.ReportCache;
import com.zhehekeji.opsys.api.common.util.ResultCode;
import com.zhehekeji.opsys.api.enm.SysconfigKey;
import com.zhehekeji.opsys.api.entity.TComplain;
import com.zhehekeji.opsys.api.entity.THomepageLog;
import com.zhehekeji.opsys.api.entity.TOrderLog;
import com.zhehekeji.opsys.api.entity.TPpvOrderLog;
import com.zhehekeji.opsys.api.entity.TSearchHistroy;
import com.zhehekeji.opsys.api.entity.TStatisticsObject;
import com.zhehekeji.opsys.api.entity.TVisitLog;
import com.zhehekeji.opsys.api.entity.TVisitLogButton;
import com.zhehekeji.opsys.api.entity.TVisitLogPage;
import com.zhehekeji.opsys.api.entity.TVodLog;
import com.zhehekeji.opsys.api.entity.TVodTimeLog;
import com.zhehekeji.opsys.api.resp.DateReportButtonLogListResp;
import com.zhehekeji.opsys.api.resp.DateReportButtonLogListResp.TVisitLogInfoButton;
import com.zhehekeji.opsys.api.resp.DateReportListResp;
import com.zhehekeji.opsys.api.resp.DateReportOrderLogListResp;
import com.zhehekeji.opsys.api.resp.DateReportOrderLogListResp.TVorderLogInfo;
import com.zhehekeji.opsys.api.resp.DateReportResp;
import com.zhehekeji.opsys.api.resp.DateReportSearchHisListResp;
import com.zhehekeji.opsys.api.resp.DateReportVodTimeListResp;
import com.zhehekeji.opsys.api.resp.DateReportVodTimeListResp.TVvodTimeLogInfo;
import com.zhehekeji.opsys.api.resp.TSearchHisLogInfo;
import com.zhehekeji.opsys.api.resp.TVisitLogInfo;
import com.zhehekeji.opsys.api.service.CommonService;
import com.zhehekeji.opsys.api.vo.ReportParam;

/**
 * @author chenweiliu chenwei.liu@163.com
 * @ClassName DataReportService
 * @Description TODO
 * @date 2015-3-26   上午10:34:14
 */
@Transactional
public class DataReportService extends CommonService implements IDataReportService {

    private final static Logger logger = LoggerFactory.getLogger(DataReportService.class);

    @Autowired
    protected OperationCache operationCache;
    @Autowired
    protected ReportCache reportCache;

    /**
     * 获取点播时长上限配置
     *
     * @return
     */
    private long getVodTimeLimit() {
        //默认4小时：4*3600=14400
        long tmpVodTimeLimit = 14400;
        try {
            String tmp = operationCache.getSysconfig(SysconfigKey.VOD_TIME_LIMIT.getKey());
            if (!StringUtils.isBlank(tmp)) {
                tmpVodTimeLimit = NumberUtils.toLong(tmp, tmpVodTimeLimit);
            }
        } catch (SQLException e) {
            logger.error("获取点播时长上限配置失败", e);
        }
        return tmpVodTimeLimit;
    }

    /**
     * 00@00@00@00
     * 从左至右依次为
     * 1、CP编号，如优朋、行云等；
     * 2、专区编号，如大片、首映、卡通等；
     * 3、收费、免费；
     * 4、节目所属分类，如电影、电视剧、少儿、综艺、体育等。
     * <p>
     * 以上编号00均预留为空值，允许部分节目个别参数为空。
     * 这是武汉李丹丹给的参数说明
     *
     * @param cpID
     * @return
     */
    private ReportParam getReportParam(String cpID) {
        ReportParam tmpReportParam = new ReportParam();
        if (StringUtils.isBlank(cpID)) {
            tmpReportParam.setCpID("0");
            return tmpReportParam;
        }
        if (cpID.indexOf("@") == -1) {
            tmpReportParam.setCpID(cpID);
            return tmpReportParam;
        }
        String[] tmpArray = cpID.split("@");

        for (int i = 0; i < tmpArray.length; i++) {
            if (i == 0) {
                String tmpActualCpID = tmpArray[0];
                if (StringUtils.isBlank(tmpActualCpID)) {
                    continue;
                }
                if (tmpActualCpID.equals("00")) {
                    tmpReportParam.setCpID("0");
                } else {
                    tmpReportParam.setCpID(tmpActualCpID);
                }
            }
            if (i == 1) {
                String tmpObjectCode = tmpArray[1];
                if (StringUtils.isBlank(tmpObjectCode)) {
                    continue;
                }
                if (tmpObjectCode.equals("00")) {
                    tmpReportParam.setObjectCode(null);
                } else {
                    tmpReportParam.setObjectCode(tmpObjectCode);
                }
            }
            if (i == 2) {
                String tmpPayFlag = tmpArray[2];
                if (StringUtils.isBlank(tmpPayFlag)) {
                    continue;
                }
                if (tmpPayFlag.equals("00")) {
                    tmpReportParam.setPayFlag(null);
                } else {
                    tmpReportParam.setPayFlag(tmpPayFlag);
                }
            }
            if (i == 3) {
                String tmpClassify = tmpArray[3];
                if (StringUtils.isBlank(tmpClassify)) {
                    continue;
                }
                if (tmpClassify.equals("00")) {
                    tmpReportParam.setClassify(null);
                } else {
                    tmpReportParam.setClassify(tmpClassify);
                }
            }
        }
        return tmpReportParam;
    }

    private String getActualAreaID(String cpID, String areaID) {
        if (StringUtils.isBlank(cpID)) {
            return areaID;
        }
        if (cpID.indexOf("@") == -1) {
            return areaID;
        }
        String tmpActualAreaID = areaID + "$" + cpID;
        if (tmpActualAreaID.length() > 64) {
            tmpActualAreaID = tmpActualAreaID.substring(0, 64);
        }
        return tmpActualAreaID;
    }

    @Override
    public DateReportResp addPageLog(String userID, String stb, int platformType, String cpID, int type,
                                      String pageIdentity, String pageName, String buttonIdentity, String buttonName,
                                      String provinceIdentity, String provinceName, String parentPageIdentity,
                                      String contentCode, String contentName, String categoryCode, String categoryName) {
        DateReportResp resp = new DateReportResp();
        try {
            TVisitLogPage tmpTVisitLog = new TVisitLogPage();
            ReportParam tmpReportParam = getReportParam(cpID);
            long tmpCpID = NumberUtils.toLong(tmpReportParam.getCpID());
            tmpTVisitLog.setCpCode(tmpCpID);

            tmpTVisitLog.setAccount(userID);
            tmpTVisitLog.setStbType(stb);
            tmpTVisitLog.setVisitTime(new Date());
            tmpTVisitLog.setType(1);
            tmpTVisitLog.setPlatformType(platformType);
            tmpTVisitLog.setPageIdentity(pageIdentity);
            tmpTVisitLog.setPageName(pageName);
            tmpTVisitLog.setProvinceIdentity(provinceIdentity);
            tmpTVisitLog.setProvinceName(provinceName);
            tmpTVisitLog.setParentPageIdentity(parentPageIdentity);
            tmpTVisitLog.setContentCode(contentCode);
            tmpTVisitLog.setContentName(contentName);
            tmpTVisitLog.setCategoryCode(categoryCode);
            tmpTVisitLog.setCategoryName(categoryName);

            entityDao.saveObj(tmpTVisitLog);
            logger.info("添加页面访问日志成功");
        } catch (Exception e) {
            logger.error("添加页面访问日志失败，系统异常，" + e.getMessage(), e);
            resp.setResultCode(ResultCode.APPLICATION_EXCEPTION);
            resp.setResultDesc("添加页面访问日志失败，系统异常");
        }
        return resp;
    }
    
    @Override
    public DateReportResp addButtonLog(String userID, String stb, int platformType, String cpID, int type,
                                      String pageIdentity, String pageName, String buttonIdentity, String buttonName,
                                      String provinceIdentity, String provinceName, String parentPageIdentity,
                                      String contentCode, String contentName, String categoryCode, String categoryName) {
        DateReportResp resp = new DateReportResp();

        try {
            TVisitLogButton tmpTVisitLog = new TVisitLogButton();
            ReportParam tmpReportParam = getReportParam(cpID);
            long tmpCpID = NumberUtils.toLong(tmpReportParam.getCpID());
            tmpTVisitLog.setCpCode(tmpCpID);

            tmpTVisitLog.setAccount(userID);
            tmpTVisitLog.setStbType(stb);
            tmpTVisitLog.setVisitTime(new Date());
            tmpTVisitLog.setType(2);
            tmpTVisitLog.setPlatformType(platformType);
            tmpTVisitLog.setPageIdentity(pageIdentity);
            tmpTVisitLog.setPageName(pageName);
            tmpTVisitLog.setButtonIdentity(buttonIdentity);
            tmpTVisitLog.setButtonName(buttonName);
            tmpTVisitLog.setProvinceIdentity(provinceIdentity);
            tmpTVisitLog.setProvinceName(provinceName);
            tmpTVisitLog.setParentPageIdentity(parentPageIdentity);
            tmpTVisitLog.setContentCode(contentCode);
            tmpTVisitLog.setContentName(contentName);
            tmpTVisitLog.setCategoryCode(categoryCode);
            tmpTVisitLog.setCategoryName(categoryName);

            entityDao.saveObj(tmpTVisitLog);
            logger.info("添加按钮访问日志成功");
        } catch (Exception e) {
            logger.error("添加按钮访问日志失败，系统异常，" + e.getMessage(), e);
            resp.setResultCode(ResultCode.APPLICATION_EXCEPTION);
            resp.setResultDesc("添加按钮访问日志失败，系统异常");
        }
        return resp;
    }
    
    @Override
    public DateReportResp addVisitLog(String userID, String stb, int platformType, String cpID, int type,
                                      String pageIdentity, String pageName, String buttonIdentity, String buttonName,
                                      String provinceIdentity, String provinceName, String parentPageIdentity,
                                      String contentCode, String contentName, String categoryCode, String categoryName,
                                      String operatorIdentity, String operatorName, String parentPageName, String utype, 
                                      String otype, String originRecommend, String ptype, String resolution) {
        DateReportResp resp = new DateReportResp();
        
        String areaIdentity = "";
		String areaName = "";
		try {
			Map<String, String> map = getAreaByUid(userID);
			areaIdentity = map.get("code");
			areaName = map.get("name");
		} catch (SQLException e1) {
			logger.error("", e1);
		}

        try {
            TVisitLog tmpTVisitLog = new TVisitLog();
            ReportParam tmpReportParam = getReportParam(cpID);
            long tmpCpID = NumberUtils.toLong(tmpReportParam.getCpID());
            tmpTVisitLog.setCpCode(tmpCpID);
            Date date = new Date();

            tmpTVisitLog.setAccount(userID);
            tmpTVisitLog.setStbType(stb);
            tmpTVisitLog.setVisitTime(date);
            tmpTVisitLog.setType(type);
            tmpTVisitLog.setPlatformType(platformType);
            tmpTVisitLog.setPageIdentity(pageIdentity);
            tmpTVisitLog.setPageName(pageName);
            tmpTVisitLog.setButtonIdentity(buttonIdentity);
            tmpTVisitLog.setButtonName(buttonName);
            tmpTVisitLog.setProvinceIdentity(provinceIdentity);
            tmpTVisitLog.setProvinceName(provinceName);
            tmpTVisitLog.setParentPageIdentity(parentPageIdentity);
            tmpTVisitLog.setContentCode(contentCode);
            tmpTVisitLog.setContentName(contentName);
            tmpTVisitLog.setCategoryCode(categoryCode);
            tmpTVisitLog.setCategoryName(categoryName);
            
            tmpTVisitLog.setOperatorIdentity(operatorIdentity);
    		tmpTVisitLog.setOperatorName(operatorName);
    		tmpTVisitLog.setAreaIdentity(areaIdentity);
    		tmpTVisitLog.setAreaName(areaName);
    		tmpTVisitLog.setParenetPageName(parentPageName);
    		
    		if(StringUtils.isNotBlank(resolution)){
    			tmpTVisitLog.setResolution(Integer.valueOf(resolution));//高标清
    		}
    		
    		if(StringUtils.isNotBlank(utype)){
    			tmpTVisitLog.setUtype(Integer.valueOf(utype));//0:其他 1:活动 2:推荐位 3:预订购 4:专题
    		}

    		if(StringUtils.isNotBlank(otype)){
    			tmpTVisitLog.setOtype(Integer.valueOf(otype));//0:异常 1:非订购用户 2:订购用户
    		}

    		if(StringUtils.isNotBlank(originRecommend)){
    			tmpTVisitLog.setOriginRecommend(Integer.valueOf(originRecommend));//0：从推荐位进入普通（默认） 1：从推荐位进入活动 2：从推荐位进入专题
    		}

    		if(StringUtils.isNotBlank(ptype)){
    			tmpTVisitLog.setPtype(Integer.valueOf(ptype));//1电竞产品，2教育产品
    		}else{
    			tmpTVisitLog.setPtype(0);
    		}

    		SimpleDateFormat sdfc = new SimpleDateFormat("yyyy-MM-dd HH:mm");
    		String datestrc = sdfc.format(date);
    		tmpTVisitLog.setVisitMinute(datestrc);

    		SimpleDateFormat sdfch = new SimpleDateFormat("yyyy-MM-dd HH");
    		String datestrch = sdfch.format(date);
    		tmpTVisitLog.setVisitHour(datestrch);

    		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
    		String datestr = sdf.format(date);
    		tmpTVisitLog.setVisitDay(datestr);

    		SimpleDateFormat sdfv = new SimpleDateFormat("yyyy-MM");
    		String datestrv = sdfv.format(date);
    		tmpTVisitLog.setVisitMonth(datestrv);

    		SimpleDateFormat sdfvv = new SimpleDateFormat("yyyy");
    		String datestrvv = sdfvv.format(date);
    		tmpTVisitLog.setVisitYear(datestrvv);

            entityDao.saveObj(tmpTVisitLog);
            logger.info("添加访问日志成功");
        } catch (Exception e) {
            logger.error("添加访问日志失败，系统异常，" + e.getMessage(), e);
            resp.setResultCode(ResultCode.APPLICATION_EXCEPTION);
            resp.setResultDesc("添加访问日志失败，系统异常");
        }
        return resp;
    }
    
    public DateReportListResp getPageLogList(String stb, String userID, int firstIndex, int maxResult) {
    	DateReportListResp resp = new DateReportListResp();
    	String resultDesc = String.format("用户[%s]获取页面访问日志列表,盒子型号[%s]", userID, stb);
    	
    	if (StringUtils.isEmpty(StringUtils.trim(userID))) {
            resultDesc = resultDesc + "，用户账号为空！";
            logger.error(resultDesc);
            resp.setResultCode(ResultCode.PARAMETER_IS_NOT_LEGAL);
            resp.setResultDesc(resultDesc);
            return resp;
        }
    	
    	String tmpCountHql = "select count(o.stbType) as count from TVisitLog o where";
    	String wherejpql = " o.account=? and o.type=1 ";
    	Object[] queryParams;
    	if (!StringUtils.isEmpty(StringUtils.trim(stb))) {
    		wherejpql += " and o.stbType=?";
    		queryParams = new Object[] {userID, stb};
    	}else {
    		queryParams = new Object[] {userID};
    	}
    	List<TVisitLogInfo> infosList = new ArrayList<TVisitLogInfo>();
    	resp.setTvLogInfos(infosList);
    	int tmpIntCount = 0;
		try {
			List<Map<String, Object>> tmpListMapCount = entityDao.getScrollDataByHql(tmpCountHql+wherejpql, queryParams, -1, -1);
            
            if (CollectionUtils.isNotEmpty(tmpListMapCount)) {
                Map<String, Object> tmpMapCount = tmpListMapCount.get(0);
                Long tmpLongCount = (Long) tmpMapCount.get("count");
                tmpIntCount = tmpLongCount.intValue();
            }
            resp.setRecordSize(tmpIntCount);
            if (tmpIntCount <= 0) {
                return resp;
            }
			
	    	List<TVisitLog> ll = entityDao.getScrollData(TVisitLog.class, firstIndex, maxResult, wherejpql, queryParams);
	    	
	    	if(CollectionUtils.isNotEmpty(ll)) {
		    	TVisitLogInfo infov;
	    		Iterator<TVisitLog> ite = ll.iterator();
	    		while(ite.hasNext()) {
	    			TVisitLog ttlLog = ite.next();
	    			infov = new TVisitLogInfo();
	    			infov.setCategoryCode(ttlLog.getCategoryCode());	    			
	    			infov.setCategoryName(ttlLog.getCategoryName());
	    			infov.setContentCode(ttlLog.getContentCode());
	    			infov.setContentName(ttlLog.getContentName());		
	    			infov.setPageIdentity(ttlLog.getPageIdentity());
	    			infov.setPageName(ttlLog.getPageName());
	    			infov.setParentPageIdentity(ttlLog.getProvinceIdentity());
	    			infov.setProvinceName(ttlLog.getProvinceName());
	    			infov.setProvinceIdentity(ttlLog.getProvinceIdentity());
	    			//infov.setPlatformType(ttlLog.getPlatformType());
	    			infov.setStb(ttlLog.getStbType());
	    			//infov.setType(ttlLog.getType());
	    			infov.setUserID(ttlLog.getAccount());
	    			//infov.setCpId(ttlLog.getCpCode());
	    			
	    			if(ttlLog.getPlatformType()==null) {
	    				infov.setPlatformType("");
	    			}else{
	    				infov.setPlatformType(String.valueOf(ttlLog.getPlatformType()));
	    			}
	    			
	    			if(ttlLog.getType()==null) {
	    				infov.setType("");
	    			}else {
	    				infov.setType(String.valueOf(ttlLog.getType()));
	    			}
	    			
	    			if(ttlLog.getCpCode()==null) {
	    				infov.setCpId("");
	    			}else {
	    				infov.setCpId(String.valueOf(ttlLog.getCpCode()));
	    			}
	    			
	    			infosList.add(infov);
		    	}
	    	}else {
	    		logger.info(resultDesc+"查询为空");
	    	}
	    	
		} catch (SQLException e) {
			logger.error(resultDesc+"异常", e);
            resp.setResultCode(ResultCode.APPLICATION_EXCEPTION);
            resp.setResultDesc(resultDesc+"异常");
		}
		
		return resp;
    }
    
    public DateReportListResp getPageLogListhn(String stb, String userID, int firstIndex, int maxResult) {
    	DateReportListResp resp = new DateReportListResp();
    	String resultDesc = String.format("用户[%s]获取页面访问日志列表,盒子型号[%s]", userID, stb);
    	
    	if (StringUtils.isEmpty(StringUtils.trim(userID))) {
            resultDesc = resultDesc + "，用户账号为空！";
            logger.error(resultDesc);
            resp.setResultCode(ResultCode.PARAMETER_IS_NOT_LEGAL);
            resp.setResultDesc(resultDesc);
            return resp;
        }
    	
    	String tmpCountHql = "select count(o.stbType) as count from TVisitLogPage o where";
    	String wherejpql = " o.account=? ";
    	Object[] queryParams;
    	if (!StringUtils.isEmpty(StringUtils.trim(stb))) {
    		wherejpql += " and o.stbType=?";
    		queryParams = new Object[] {userID, stb};
    	}else {
    		queryParams = new Object[] {userID};
    	}
    	List<TVisitLogInfo> infosList = new ArrayList<TVisitLogInfo>();
    	resp.setTvLogInfos(infosList);
    	int tmpIntCount = 0;
		try {
			List<Map<String, Object>> tmpListMapCount = entityDao.getScrollDataByHql(tmpCountHql+wherejpql, queryParams, -1, -1);
            
            if (CollectionUtils.isNotEmpty(tmpListMapCount)) {
                Map<String, Object> tmpMapCount = tmpListMapCount.get(0);
                Long tmpLongCount = (Long) tmpMapCount.get("count");
                tmpIntCount = tmpLongCount.intValue();
            }
            resp.setRecordSize(tmpIntCount);
            if (tmpIntCount <= 0) {
                return resp;
            }
			
	    	List<TVisitLogPage> ll = entityDao.getScrollData(TVisitLogPage.class, firstIndex, maxResult, wherejpql, queryParams);
	    	
	    	if(CollectionUtils.isNotEmpty(ll)) {
		    	TVisitLogInfo infov;
	    		Iterator<TVisitLogPage> ite = ll.iterator();
	    		while(ite.hasNext()) {
	    			TVisitLogPage ttlLog = ite.next();
	    			infov = new TVisitLogInfo();
	    			infov.setCategoryCode(ttlLog.getCategoryCode());	    			
	    			infov.setCategoryName(ttlLog.getCategoryName());
	    			infov.setContentCode(ttlLog.getContentCode());
	    			infov.setContentName(ttlLog.getContentName());		
	    			infov.setPageIdentity(ttlLog.getPageIdentity());
	    			infov.setPageName(ttlLog.getPageName());
	    			infov.setParentPageIdentity(ttlLog.getProvinceIdentity());
	    			infov.setProvinceName(ttlLog.getProvinceName());
	    			infov.setProvinceIdentity(ttlLog.getProvinceIdentity());
	    			//infov.setPlatformType(ttlLog.getPlatformType());
	    			infov.setStb(ttlLog.getStbType());
	    			//infov.setType(ttlLog.getType());
	    			infov.setUserID(ttlLog.getAccount());
	    			//infov.setCpId(ttlLog.getCpCode());
	    			
	    			if(ttlLog.getPlatformType()==null) {
	    				infov.setPlatformType("");
	    			}else{
	    				infov.setPlatformType(String.valueOf(ttlLog.getPlatformType()));
	    			}
	    			
	    			if(ttlLog.getType()==null) {
	    				infov.setType("");
	    			}else {
	    				infov.setType(String.valueOf(ttlLog.getType()));
	    			}
	    			
	    			if(ttlLog.getCpCode()==null) {
	    				infov.setCpId("");
	    			}else {
	    				infov.setCpId(String.valueOf(ttlLog.getCpCode()));
	    			}
	    			
	    			infosList.add(infov);
		    	}
	    	}else {
	    		logger.info(resultDesc+"查询为空");
	    	}
	    	
		} catch (SQLException e) {
			logger.error(resultDesc+"异常", e);
            resp.setResultCode(ResultCode.APPLICATION_EXCEPTION);
            resp.setResultDesc(resultDesc+"异常");
		}
		
		return resp;
    }

    @Override
    public DateReportResp addVodLog(String userID, String contentCode,
                                    String contentName, String cpID, String productCode, int type,
                                    String seriesCode, String seriesName, String productName,
                                    int category, int resolution, String areaID, int epgPlatformType, String stb) {
        DateReportResp resp = new DateReportResp();
        if (StringUtils.isBlank(contentCode)) {
            logger.error("添加详情页访问次数日志失败，内容编码非法");
            resp.setResultCode(ResultCode.PARAMETER_IS_NOT_LEGAL);
            resp.setResultDesc("添加详情页访问次数日志失败，内容编码非法");
            return resp;
        }
        try {
            TVodLog tmpTVodLog = new TVodLog();

            ReportParam tmpReportParam = getReportParam(cpID);
            long tmpCpID = NumberUtils.toLong(tmpReportParam.getCpID());
            tmpTVodLog.setCpCode(tmpCpID);
            tmpTVodLog.setProductName(productName);
            tmpTVodLog.setProductCode(productCode);

            String tmpObjectCode = tmpReportParam.getObjectCode();
            if (!StringUtils.isBlank(tmpObjectCode)) {
                tmpTVodLog.setProductCode(tmpObjectCode);
                //TStatisticsObject tmpTStatisticsObject = entityDao.get(TStatisticsObject.class, "o.code=?1 and o.cpCode=?2", new Object[]{tmpObjectCode, tmpCpID});
                TStatisticsObject tmpTStatisticsObject = reportCache.getStatisticsObject(tmpObjectCode, tmpCpID);
                if (tmpTStatisticsObject != null) {
                    tmpTVodLog.setProductName(tmpTStatisticsObject.getName());
                }
            }

            tmpTVodLog.setCname(contentName);
            tmpTVodLog.setCid(contentCode);
            tmpTVodLog.setType(type);
            tmpTVodLog.setAccount(userID);
            tmpTVodLog.setVisitTime(new Date());
            tmpTVodLog.setSeriesCode(seriesCode);
            tmpTVodLog.setSeriesName(seriesName);
            tmpTVodLog.setCategory(category);
            tmpTVodLog.setResolution(resolution);
            tmpTVodLog.setAreaId(getActualAreaID(cpID, areaID));
            tmpTVodLog.setEpgPlatformType(epgPlatformType);
            tmpTVodLog.setStbType(stb);
            entityDao.saveObj(tmpTVodLog);
            logger.info("添加详情页访问次数日志成功");
        } catch (Exception e) {
            logger.error("添加详情页访问次数日志失败，系统异常，" + e.getMessage(), e);
            resp.setResultCode(ResultCode.APPLICATION_EXCEPTION);
            resp.setResultDesc("添加详情页访问次数日志失败，系统异常");
        }
        return resp;
    }


    @Override
    public DateReportResp addVodTimeLog(String userID, String stb, int platformType, String cpID, int type,
                                        String pageIdentity, String pageName,
                                        String provinceIdentity, String provinceName, String parentPageIdentity,
                                        String contentCode, String contentName, String categoryCode, String categoryName,
                                        Long playTime, String seriesCode, String seriesName, String operatorIdentity, String operatorName,String utype,String ptype, String resolution) {
        DateReportResp resp = new DateReportResp();
        Date currentDate = new Date();
        if (StringUtils.isBlank(contentCode)) {
            logger.error("添加影片访问时长日志失败，内容编码非法");
            resp.setResultCode(ResultCode.PARAMETER_IS_NOT_LEGAL);
            resp.setResultDesc("添加影片访问时长日志失败，内容编码非法");
            return resp;
        }
        //if (StringUtils.isBlank(startTime)) {
        //    logger.error("添加影片访问时长日志失败，起播时间非法");
        //    resp.setResultCode(ResultCode.PARAMETER_IS_NOT_LEGAL);
        //    resp.setResultDesc("添加影片访问时长日志失败，起播时间非法");
        //    return resp;
        //}
        String timeTemplate = "yyyyMMddHHmmss";
        //Date startDate = null;
        //try {
        //    startDate = DateUtils.parseDate(startTime, new String[]{timeTemplate});
        //} catch (ParseException e) {
        //    logger.error("添加影片访问时长日志失败，起播时间格式必须为" + timeTemplate);
        //    resp.setResultCode(ResultCode.PARAMETER_IS_NOT_LEGAL);
        //    resp.setResultDesc("添加影片访问时长日志失败，起播时间格式必须为" + timeTemplate);
        //    return resp;
        //}
        //Date endDate = null;
        //if (StringUtils.isBlank(endTime)) {
        //    endDate = currentDate;
        //} else {
        //    try {
        //        endDate = DateUtils.parseDate(endTime, new String[]{timeTemplate});
        //    } catch (ParseException e) {
        //        logger.error("添加影片访问时长日志失败，止播时间格式必须为" + timeTemplate);
        //        resp.setResultCode(ResultCode.PARAMETER_IS_NOT_LEGAL);
        //        resp.setResultDesc("添加影片访问时长日志失败，止播时间格式必须为" + timeTemplate);
        //        return resp;
        //    }
        //}
        ////时长（秒）
        //Long times = (endDate.getTime() - startDate.getTime()) / 1000;
        //if (times < 0) {
        //    times = 0L;
        //}

        //2017-06-28添加
        long tmpVodTimeLimit = getVodTimeLimit();
        if (playTime > tmpVodTimeLimit) {
            logger.error(String.format("添加影片访问时长日志失败，观看影片时长超过[%s]秒，实际观看时长[%s]秒", tmpVodTimeLimit, playTime));
            resp.setResultCode(ResultCode.PARAMETER_IS_NOT_LEGAL);
            resp.setResultDesc(String.format("添加影片访问时长日志失败，观看影片时长超过[%s]秒，实际观看时长[%s]秒", tmpVodTimeLimit, playTime));
            return resp;
        }
        
        String areaIdentity = "";
		String areaName = "";
		try {
			Map<String, String> map = getAreaByUid(userID);
			areaIdentity = map.get("code");
			areaName = map.get("name");
		} catch (SQLException e1) {
			logger.error("", e1);
		}

        try {
            TVodTimeLog tmpTVodTimeLog = new TVodTimeLog();

            ReportParam tmpReportParam = getReportParam(cpID);
            long tmpCpID = NumberUtils.toLong(tmpReportParam.getCpID());
            tmpTVodTimeLog.setCpCode(tmpCpID);

            //String tmpObjectCode = tmpReportParam.getObjectCode();
            //if (!StringUtils.isBlank(tmpObjectCode)) {
            //    tmpTVodTimeLog.setProductCode(tmpObjectCode);
            //    //TStatisticsObject tmpTStatisticsObject = entityDao.get(TStatisticsObject.class, "o.code=?1 and o.cpCode=?2", new Object[]{tmpObjectCode, tmpCpID});
            //    TStatisticsObject tmpTStatisticsObject = reportCache.getStatisticsObject(tmpObjectCode, tmpCpID);
            //    if (tmpTStatisticsObject != null) {
            //        tmpTVodTimeLog.setProductName(tmpTStatisticsObject.getName());
            //    }
            //}

            tmpTVodTimeLog.setCname(contentName);
            tmpTVodTimeLog.setCid(contentCode);
            tmpTVodTimeLog.setType(type);
            tmpTVodTimeLog.setAccount(userID);
            tmpTVodTimeLog.setVisitTime(currentDate);
            //tmpTVodTimeLog.setStartTime(startDate);
            //tmpTVodTimeLog.setEndTime(endDate);
            tmpTVodTimeLog.setTimes(playTime);
            //tmpTVodTimeLog.setSeriesCode(seriesCode);
            //tmpTVodTimeLog.setSeriesName(seriesName);
            //tmpTVodTimeLog.setResolution(resolution);
            //tmpTVodTimeLog.setAreaId(getActualAreaID(cpID, areaID));
            //tmpTVodTimeLog.setEpgPlatformType(epgPlatformType);
            tmpTVodTimeLog.setPlatformType(platformType);
            tmpTVodTimeLog.setPageIdentity(pageIdentity);
            tmpTVodTimeLog.setPageName(pageName);
            tmpTVodTimeLog.setProvinceIdentity(provinceIdentity);
            tmpTVodTimeLog.setProvinceName(provinceName);
            tmpTVodTimeLog.setParentPageIdentity(parentPageIdentity);
            tmpTVodTimeLog.setContentCode(contentCode);
            tmpTVodTimeLog.setContentName(contentName);
            tmpTVodTimeLog.setCategoryCode(categoryCode);
            tmpTVodTimeLog.setCategoryName(categoryName);
            tmpTVodTimeLog.setStbType(stb);
            
            tmpTVodTimeLog.setOperatorIdentity(operatorIdentity);
    		tmpTVodTimeLog.setOperatorName(operatorName);
    		tmpTVodTimeLog.setAreaIdentity(areaIdentity);
    		tmpTVodTimeLog.setAreaName(areaName);
    		
    		if(StringUtils.isNotBlank(resolution)){
    			tmpTVodTimeLog.setResolution(Integer.valueOf(resolution));//高标清
    		}
    		
    		if(StringUtils.isNotBlank(utype)){
    			tmpTVodTimeLog.setUtype(Integer.valueOf(utype));//0:其他 1:活动 2:推荐位 3:预订购 4:专题
    		}

    		if(StringUtils.isNotBlank(ptype)){
    			tmpTVodTimeLog.setPtype(Integer.valueOf(ptype));//1电竞产品，2教育产品
    		}else{
    			tmpTVodTimeLog.setPtype(0);
    		}

    		SimpleDateFormat sdfc = new SimpleDateFormat("yyyy-MM-dd HH:mm");
    		String datestrc = sdfc.format(currentDate);
    		tmpTVodTimeLog.setVodtimeMinute(datestrc);

    		SimpleDateFormat sdfch = new SimpleDateFormat("yyyy-MM-dd HH");
    		String datestrch = sdfch.format(currentDate);
    		tmpTVodTimeLog.setVodtimeHour(datestrch);

    		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
    		String datestr = sdf.format(currentDate);
    		tmpTVodTimeLog.setVodtimeDay(datestr);

    		SimpleDateFormat sdfv = new SimpleDateFormat("yyyy-MM");
    		String datestrv = sdfv.format(currentDate);
    		tmpTVodTimeLog.setVodtimeMonth(datestrv);

    		SimpleDateFormat sdfvv = new SimpleDateFormat("yyyy");
    		String datestrvv = sdfvv.format(currentDate);
    		tmpTVodTimeLog.setVodtimeYear(datestrvv);
            
            entityDao.saveObj(tmpTVodTimeLog);
            logger.info("添加影片访问时长日志成功");
        } catch (Exception e) {
            logger.error("添加影片访问时长日志失败，系统异常，" + e.getMessage(), e);
            resp.setResultCode(ResultCode.APPLICATION_EXCEPTION);
            resp.setResultDesc("添加详情页访问次数日志失败，系统异常");
        }
        return resp;
    }

    @Override
    public DateReportResp addOrderLog(String userID, String stb, int action, int platformType, String cpID, int type,
                                      String pageIdentity, String pageName,
                                      String provinceIdentity, String provinceName, String parentPageIdentity,
                                      String contentCode, String contentName, String categoryCode, String categoryName,
                                      double origPrice, double price, String operatorIdentity, String operatorName,String ptype, String resolution, String comFrom) {
        DateReportResp resp = new DateReportResp();
        //if (StringUtils.isBlank(productCode)) {
        //    logger.error("添加订购日志失败，产品编码非法");
        //    resp.setResultCode(ResultCode.PARAMETER_IS_NOT_LEGAL);
        //    resp.setResultDesc("添加订购日志失败，产品编码非法");
        //    return resp;
        //}
        String areaIdentity = "";
        String areaName = "";
        try {
			Map<String, String> map = getAreaByUid(userID);
			areaIdentity = map.get("code");
			areaName = map.get("name");
		} catch (SQLException e1) {
			logger.error("", e1);
		}
        
        try {
            TOrderLog tmpTOrderLog = new TOrderLog();

            ReportParam tmpReportParam = getReportParam(cpID);
            long tmpCpID = NumberUtils.toLong(tmpReportParam.getCpID());
            tmpTOrderLog.setCpCode(tmpCpID);

            //tmpTOrderLog.setProductName(productName);
            //tmpTOrderLog.setProductCode(productCode);

            //String tmpObjectCode = tmpReportParam.getObjectCode();
            //if (!StringUtils.isBlank(tmpObjectCode)) {
            //    tmpTOrderLog.setProductCode(tmpObjectCode);
            //    //TStatisticsObject tmpTStatisticsObject = entityDao.get(TStatisticsObject.class, "o.code=?1 and o.cpCode=?2", new Object[]{tmpObjectCode, tmpCpID});
            //    TStatisticsObject tmpTStatisticsObject = reportCache.getStatisticsObject(tmpObjectCode, tmpCpID);
            //    if (tmpTStatisticsObject != null) {
            //        tmpTOrderLog.setProductName(tmpTStatisticsObject.getName());
            //    }
            //}

            Date date = new Date();
            tmpTOrderLog.setAccount(userID);
            tmpTOrderLog.setAction(action);
            tmpTOrderLog.setCreateTime(date);
            tmpTOrderLog.setType(type);
            tmpTOrderLog.setOrigPrice(origPrice);
            tmpTOrderLog.setPrice(price);
            //tmpTOrderLog.setComeFrom(comeFrom);
            //tmpTOrderLog.setResolution(resolution);
            //tmpTOrderLog.setAreaId(getActualAreaID(cpID, areaID));
            //tmpTOrderLog.setEpgPlatformType(epgPlatformType);
            tmpTOrderLog.setStbType(stb);
            tmpTOrderLog.setPlatformType(platformType);
            tmpTOrderLog.setPageIdentity(pageIdentity);
            tmpTOrderLog.setPageName(pageName);
            tmpTOrderLog.setProvinceIdentity(provinceIdentity);
            tmpTOrderLog.setProvinceName(provinceName);
            tmpTOrderLog.setParentPageIdentity(parentPageIdentity);
            tmpTOrderLog.setContentCode(contentCode);
            tmpTOrderLog.setContentName(contentName);
            tmpTOrderLog.setCategoryCode(categoryCode);
            tmpTOrderLog.setCategoryName(categoryName);
            
            tmpTOrderLog.setOperatorIdentity(operatorIdentity);
            tmpTOrderLog.setOperatorName(operatorName);
            tmpTOrderLog.setAreaIdentity(areaIdentity);
            tmpTOrderLog.setAreaName(areaName);
    		
    		if(StringUtils.isNotBlank(resolution)){
    			tmpTOrderLog.setResolution(Integer.valueOf(resolution));
    		}
    		
    		if(StringUtils.isNotBlank(comFrom)) {
    			tmpTOrderLog.setComeFrom(Integer.valueOf(comFrom));
    		}
    		
    		if(StringUtils.isNotBlank(ptype)){
    			tmpTOrderLog.setPtype(Integer.valueOf(ptype));//1电竞产品，2教育产品
    		}else{
    			tmpTOrderLog.setPtype(0);
    		}
    		
    		SimpleDateFormat sdfc = new SimpleDateFormat("yyyy-MM-dd HH:mm");
    		String datestrc = sdfc.format(date);
    		tmpTOrderLog.setOrderMinute(datestrc);

    		SimpleDateFormat sdfch = new SimpleDateFormat("yyyy-MM-dd HH");
    		String datestrch = sdfch.format(date);
    		tmpTOrderLog.setOrderHour(datestrch);

    		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
    		String datestr = sdf.format(date);
    		tmpTOrderLog.setOrderDay(datestr);

    		SimpleDateFormat sdfv = new SimpleDateFormat("yyyy-MM");
    		String datestrv = sdfv.format(date);
    		tmpTOrderLog.setOrderMonth(datestrv);

    		SimpleDateFormat sdfvv = new SimpleDateFormat("yyyy");
    		String datestrvv = sdfvv.format(date);
    		tmpTOrderLog.setOrderYear(datestrvv);
            
            entityDao.saveObj(tmpTOrderLog);
            logger.info("添加订购日志成功");
        } catch (Exception e) {
            logger.error("添加订购日志失败，系统异常，" + e.getMessage(), e);
            resp.setResultCode(ResultCode.APPLICATION_EXCEPTION);
            resp.setResultDesc("添加订购日志成功，系统异常");
        }
        return resp;
    }

    @Override
    public DateReportResp addComplainLog(String userID, String stb, String ip, String productCode,
                                         String productName, String cpID, int type, int resolution, String areaID, int epgPlatformType) {
        DateReportResp resp = new DateReportResp();
        if (StringUtils.isBlank(productCode)) {
            logger.error("添加投诉日志失败，产品编码非法");
            resp.setResultCode(ResultCode.PARAMETER_IS_NOT_LEGAL);
            resp.setResultDesc("添加投诉日志失败，产品编码非法");
            return resp;
        }
        try {
            TComplain tmpTComplain = new TComplain();

            ReportParam tmpReportParam = getReportParam(cpID);
            long tmpCpID = NumberUtils.toLong(tmpReportParam.getCpID());
            tmpTComplain.setCpCode(tmpCpID);
            tmpTComplain.setObjectName(productName);
            tmpTComplain.setObjectCode(productCode);

            String tmpObjectCode = tmpReportParam.getObjectCode();
            if (!StringUtils.isBlank(tmpObjectCode)) {
                tmpTComplain.setObjectCode(tmpObjectCode);
                //TStatisticsObject tmpTStatisticsObject = entityDao.get(TStatisticsObject.class, "o.code=?1 and o.cpCode=?2", new Object[]{tmpObjectCode, tmpCpID});
                TStatisticsObject tmpTStatisticsObject = reportCache.getStatisticsObject(tmpObjectCode, tmpCpID);
                if (tmpTStatisticsObject != null) {
                    tmpTComplain.setObjectName(tmpTStatisticsObject.getName());
                }
            }

            tmpTComplain.setAccount(userID);
            tmpTComplain.setComplainIp(ip);
            tmpTComplain.setComplainTime(new Date());
            tmpTComplain.setStbType(stb);
            tmpTComplain.setType(type);
            tmpTComplain.setResolution(resolution);
            tmpTComplain.setAreaId(getActualAreaID(cpID, areaID));
            tmpTComplain.setEpgPlatformType(epgPlatformType);
            entityDao.saveObj(tmpTComplain);
            logger.info("添加投诉日志成功");
        } catch (Exception e) {
            logger.error("添加投诉日志失败，系统异常，" + e.getMessage(), e);
            resp.setResultCode(ResultCode.APPLICATION_EXCEPTION);
            resp.setResultDesc("添加投诉日志失败，系统异常");
        }
        return resp;

    }

    @Override
    public DateReportResp addPPVOrderLog(String userID, String contentCode,
                                         String contentName, double origPrice, double price, int resolution,
                                         int comeFrom, String cpID, String areaID, String productCode,
                                         String productName, int epgPlatformType, String stb) {
        DateReportResp resp = new DateReportResp();
        if (StringUtils.isBlank(contentCode)) {
            logger.error("添加PPV订购日志失败，内容编码非法");
            resp.setResultCode(ResultCode.PARAMETER_IS_NOT_LEGAL);
            resp.setResultDesc("添加PPV订购日志失败，内容编码非法");
            return resp;
        }
        try {
            TPpvOrderLog tmpTPpvOrderLog = new TPpvOrderLog();

            ReportParam tmpReportParam = getReportParam(cpID);
            long tmpCpID = NumberUtils.toLong(tmpReportParam.getCpID());
            tmpTPpvOrderLog.setCpCode(tmpCpID);
            tmpTPpvOrderLog.setProductName(productName);
            tmpTPpvOrderLog.setProductCode(productCode);

            String tmpObjectCode = tmpReportParam.getObjectCode();
            if (!StringUtils.isBlank(tmpObjectCode)) {
                tmpTPpvOrderLog.setProductCode(tmpObjectCode);
                //TStatisticsObject tmpTStatisticsObject = entityDao.get(TStatisticsObject.class, "o.code=?1 and o.cpCode=?2", new Object[]{tmpObjectCode, tmpCpID});
                TStatisticsObject tmpTStatisticsObject = reportCache.getStatisticsObject(tmpObjectCode, tmpCpID);
                if (tmpTStatisticsObject != null) {
                    tmpTPpvOrderLog.setProductName(tmpTStatisticsObject.getName());
                }
            }

            tmpTPpvOrderLog.setAccount(userID);
            tmpTPpvOrderLog.setCid(contentCode);
            tmpTPpvOrderLog.setCname(contentName);
            tmpTPpvOrderLog.setCreateTime(new Date());
            tmpTPpvOrderLog.setOrigPrice(origPrice);
            tmpTPpvOrderLog.setPrice(price);
            tmpTPpvOrderLog.setResolution(resolution);
            tmpTPpvOrderLog.setComeFrom(comeFrom);
            tmpTPpvOrderLog.setAreaId(getActualAreaID(cpID, areaID));
            tmpTPpvOrderLog.setEpgPlatformType(epgPlatformType);
            tmpTPpvOrderLog.setStbType(stb);
            entityDao.saveObj(tmpTPpvOrderLog);
            logger.info("添加PPV订购日志成功");
        } catch (Exception e) {
            logger.error("添加PPV订购日志失败，系统异常，" + e.getMessage(), e);
            resp.setResultCode(ResultCode.APPLICATION_EXCEPTION);
            resp.setResultDesc("添加PPV订购日志失败，系统异常");
        }
        return resp;
    }

    @Override
    public DateReportResp addHomepageLog(String userID, String homepageCode, String homepageName,
                                         String location, int resolution, String cpID, String areaID, int epgPlatformType, String stb) {
        DateReportResp resp = new DateReportResp();
        if (StringUtils.isBlank(homepageCode)) {
            logger.error("添加首页访问日志失败，首页编码非法");
            resp.setResultCode(ResultCode.PARAMETER_IS_NOT_LEGAL);
            resp.setResultDesc("添加首页访问日志失败，首页编码非法");
            return resp;
        }
        try {
            THomepageLog tmpTHomepageLog = new THomepageLog();

            ReportParam tmpReportParam = getReportParam(cpID);
            long tmpCpID = NumberUtils.toLong(tmpReportParam.getCpID());
            tmpTHomepageLog.setCpCode(tmpCpID);
            tmpTHomepageLog.setHomepageName(homepageName);
            tmpTHomepageLog.setHomepageCode(homepageCode);

            String tmpObjectCode = tmpReportParam.getObjectCode();
            if (!StringUtils.isBlank(tmpObjectCode)) {
                tmpTHomepageLog.setHomepageCode(tmpObjectCode);
                //TStatisticsObject tmpTStatisticsObject = entityDao.get(TStatisticsObject.class, "o.code=?1 and o.cpCode=?2", new Object[]{tmpObjectCode, tmpCpID});
                TStatisticsObject tmpTStatisticsObject = reportCache.getStatisticsObject(tmpObjectCode, tmpCpID);
                if (tmpTStatisticsObject != null) {
                    tmpTHomepageLog.setHomepageName(tmpTStatisticsObject.getName());
                }
            }

            tmpTHomepageLog.setAccount(userID);
            tmpTHomepageLog.setAreaId(getActualAreaID(cpID, areaID));
            tmpTHomepageLog.setEpgPlatformType(epgPlatformType);
            tmpTHomepageLog.setLocation(location);
            tmpTHomepageLog.setResolution(resolution);
            tmpTHomepageLog.setStbType(stb);
            tmpTHomepageLog.setVisitTime(new Date());
            entityDao.saveObj(tmpTHomepageLog);
            logger.info("添加首页访问日志成功");
        } catch (Exception e) {
            logger.error("添加首页访问日志失败，系统异常，" + e.getMessage(), e);
            resp.setResultCode(ResultCode.APPLICATION_EXCEPTION);
            resp.setResultDesc("添加首页访问日志失败，系统异常");
        }
        return resp;
    }
    
    @Override
	public DateReportButtonLogListResp getButtonLogList(String stb, String userID, int firstIndex, int maxResult) {
		DateReportButtonLogListResp resp = new DateReportButtonLogListResp();
    	String resultDesc = String.format("用户[%s]获取按钮访问日志列表,盒子型号[%s]", userID, stb);
    	
    	if (StringUtils.isEmpty(StringUtils.trim(userID))) {
            resultDesc = resultDesc + "，用户账号为空！";
            logger.error(resultDesc);
            resp.setResultCode(ResultCode.PARAMETER_IS_NOT_LEGAL);
            resp.setResultDesc(resultDesc);
            return resp;
        }
    	
    	String tmpCountHql = "select count(o.id) as count from TVisitLog o where";
    	String wherejpql = " o.account=? and o.type=2 ";
    	Object[] queryParams;
    	if (!StringUtils.isEmpty(StringUtils.trim(stb))) {
    		wherejpql += " and o.stbType=?";
    		queryParams = new Object[] {userID, stb};
    	}else {
    		queryParams = new Object[] {userID};
    	}
    	int tmpIntCount = 0;
    	List<TVisitLogInfoButton> infosList = new ArrayList<TVisitLogInfoButton>();
    	resp.setTvLogInfos(infosList);
		try {
			List<Map<String, Object>> tmpListMapCount = entityDao.getScrollDataByHql(tmpCountHql+wherejpql, queryParams, -1, -1);
            
            if (CollectionUtils.isNotEmpty(tmpListMapCount)) {
                Map<String, Object> tmpMapCount = tmpListMapCount.get(0);
                Long tmpLongCount = (Long) tmpMapCount.get("count");
                tmpIntCount = tmpLongCount.intValue();
            }
            resp.setRecordSize(tmpIntCount);
            if (tmpIntCount <= 0) {
                return resp;
            }
			
	    	List<TVisitLog> ll = entityDao.getScrollData(TVisitLog.class, firstIndex, maxResult, wherejpql, queryParams);
	    	
	    	if(CollectionUtils.isNotEmpty(ll)) {
		    	TVisitLogInfoButton infov;
	    		Iterator<TVisitLog> ite = ll.iterator();
	    		while(ite.hasNext()) {
	    			TVisitLog ttlLog = ite.next();
	    			infov = new TVisitLogInfoButton();
	    			infov.setCategoryCode(ttlLog.getCategoryCode());	    			
	    			infov.setCategoryName(ttlLog.getCategoryName());
	    			infov.setContentCode(ttlLog.getContentCode());
	    			infov.setContentName(ttlLog.getContentName());
	    			infov.setPageIdentity(ttlLog.getPageIdentity());
	    			infov.setPageName(ttlLog.getPageName());
	    			infov.setButtonIdentity(ttlLog.getButtonIdentity());
	    			infov.setButtonName(ttlLog.getButtonName());
	    			infov.setParentPageIdentity(ttlLog.getProvinceIdentity());
	    			infov.setProvinceName(ttlLog.getProvinceName());
	    			infov.setProvinceIdentity(ttlLog.getProvinceIdentity());
	    			//infov.setPlatformType(ttlLog.getPlatformType());
	    			infov.setStb(ttlLog.getStbType());
	    			//infov.setType(ttlLog.getType());
	    			infov.setUserID(ttlLog.getAccount());
	    			//infov.setCpId(ttlLog.getCpCode());  	
	    			
	    			if(ttlLog.getPlatformType()==null) {
	    				infov.setPlatformType("");
	    			}else{
	    				infov.setPlatformType(String.valueOf(ttlLog.getPlatformType()));
	    			}
	    			
	    			if(ttlLog.getType()==null) {
	    				infov.setType("");
	    			}else {
	    				infov.setType(String.valueOf(ttlLog.getType()));
	    			}
	    			
	    			if(ttlLog.getCpCode()==null) {
	    				infov.setCpId("");
	    			}else {
	    				infov.setCpId(String.valueOf(ttlLog.getCpCode()));
	    			}
	    			
	    			infosList.add(infov);
		    	}
	    	}else {
	    		logger.info(resultDesc+"查询为空");
	    	}
	    	
		} catch (SQLException e) {
			logger.error(resultDesc+"异常", e);
            resp.setResultCode(ResultCode.APPLICATION_EXCEPTION);
            resp.setResultDesc(resultDesc+"异常");
		}
		
		return resp;
    }

	@Override
	public DateReportButtonLogListResp getButtonLogListhn(String stb, String userID, int firstIndex, int maxResult) {
		DateReportButtonLogListResp resp = new DateReportButtonLogListResp();
    	String resultDesc = String.format("用户[%s]获取按钮访问日志列表,盒子型号[%s]", userID, stb);
    	
    	if (StringUtils.isEmpty(StringUtils.trim(userID))) {
            resultDesc = resultDesc + "，用户账号为空！";
            logger.error(resultDesc);
            resp.setResultCode(ResultCode.PARAMETER_IS_NOT_LEGAL);
            resp.setResultDesc(resultDesc);
            return resp;
        }
    	
    	String tmpCountHql = "select count(o.id) as count from TVisitLogButton o where";
    	String wherejpql = " o.account=? ";
    	Object[] queryParams;
    	if (!StringUtils.isEmpty(StringUtils.trim(stb))) {
    		wherejpql += " and o.stbType=?";
    		queryParams = new Object[] {userID, stb};
    	}else {
    		queryParams = new Object[] {userID};
    	}
    	int tmpIntCount = 0;
    	List<TVisitLogInfoButton> infosList = new ArrayList<TVisitLogInfoButton>();
    	resp.setTvLogInfos(infosList);
		try {
			List<Map<String, Object>> tmpListMapCount = entityDao.getScrollDataByHql(tmpCountHql+wherejpql, queryParams, -1, -1);
            
            if (CollectionUtils.isNotEmpty(tmpListMapCount)) {
                Map<String, Object> tmpMapCount = tmpListMapCount.get(0);
                Long tmpLongCount = (Long) tmpMapCount.get("count");
                tmpIntCount = tmpLongCount.intValue();
            }
            resp.setRecordSize(tmpIntCount);
            if (tmpIntCount <= 0) {
                return resp;
            }
			
	    	List<TVisitLogButton> ll = entityDao.getScrollData(TVisitLogButton.class, firstIndex, maxResult, wherejpql, queryParams);
	    	
	    	if(CollectionUtils.isNotEmpty(ll)) {
		    	TVisitLogInfoButton infov;
	    		Iterator<TVisitLogButton> ite = ll.iterator();
	    		while(ite.hasNext()) {
	    			TVisitLogButton ttlLog = ite.next();
	    			infov = new TVisitLogInfoButton();
	    			infov.setCategoryCode(ttlLog.getCategoryCode());	    			
	    			infov.setCategoryName(ttlLog.getCategoryName());
	    			infov.setContentCode(ttlLog.getContentCode());
	    			infov.setContentName(ttlLog.getContentName());
	    			infov.setPageIdentity(ttlLog.getPageIdentity());
	    			infov.setPageName(ttlLog.getPageName());
	    			infov.setButtonIdentity(ttlLog.getButtonIdentity());
	    			infov.setButtonName(ttlLog.getButtonName());
	    			infov.setParentPageIdentity(ttlLog.getProvinceIdentity());
	    			infov.setProvinceName(ttlLog.getProvinceName());
	    			infov.setProvinceIdentity(ttlLog.getProvinceIdentity());
	    			//infov.setPlatformType(ttlLog.getPlatformType());
	    			infov.setStb(ttlLog.getStbType());
	    			//infov.setType(ttlLog.getType());
	    			infov.setUserID(ttlLog.getAccount());
	    			//infov.setCpId(ttlLog.getCpCode());  	
	    			
	    			if(ttlLog.getPlatformType()==null) {
	    				infov.setPlatformType("");
	    			}else{
	    				infov.setPlatformType(String.valueOf(ttlLog.getPlatformType()));
	    			}
	    			
	    			if(ttlLog.getType()==null) {
	    				infov.setType("");
	    			}else {
	    				infov.setType(String.valueOf(ttlLog.getType()));
	    			}
	    			
	    			if(ttlLog.getCpCode()==null) {
	    				infov.setCpId("");
	    			}else {
	    				infov.setCpId(String.valueOf(ttlLog.getCpCode()));
	    			}
	    			
	    			infosList.add(infov);
		    	}
	    	}else {
	    		logger.info(resultDesc+"查询为空");
	    	}
	    	
		} catch (SQLException e) {
			logger.error(resultDesc+"异常", e);
            resp.setResultCode(ResultCode.APPLICATION_EXCEPTION);
            resp.setResultDesc(resultDesc+"异常");
		}
		
		return resp;
    }

	@Override
	public DateReportResp addVisitLog(String userID, String stb, String cpID, int type, String productName,
			String productCode, int resolution, String areaID, String provinceIdentity, String provinceName,
			String parentPageIdentity, int epgPlatformType) {

        DateReportResp resp = new DateReportResp();
        
        try {
            TVisitLog tmpTVisitLog = new TVisitLog();
            ReportParam tmpReportParam = getReportParam(cpID);
            long tmpCpID = NumberUtils.toLong(tmpReportParam.getCpID());
            tmpTVisitLog.setCpCode(tmpCpID);

            tmpTVisitLog.setProductName(productName);
            tmpTVisitLog.setProductCode(productCode);
            tmpTVisitLog.setAccount(userID);
            tmpTVisitLog.setStbType(stb);
            tmpTVisitLog.setType(type);
            tmpTVisitLog.setResolution(resolution);
            tmpTVisitLog.setAreaId(getActualAreaID(cpID, areaID));
            tmpTVisitLog.setEpgPlatformType(epgPlatformType);
           
            tmpTVisitLog.setVisitTime(new Date());

            entityDao.saveObj(tmpTVisitLog);
            logger.info("添加用户访问日志成功");
        } catch (Exception e) {
            logger.error("添加用户访问日志失败，系统异常，" + e.getMessage(), e);
            resp.setResultCode(ResultCode.APPLICATION_EXCEPTION);
            resp.setResultDesc("添加用户访问日志失败，系统异常");
        }
        return resp;
    
	}

	@Override
	public DateReportVodTimeListResp getVodTimeLogList(String stb, String userID, int firstIndex, int maxResult) {
		DateReportVodTimeListResp resp = new DateReportVodTimeListResp();
    	String resultDesc = String.format("用户[%s]获取影片访问时长日志列表,盒子型号[%s]", userID, stb);
    	
    	if (StringUtils.isEmpty(StringUtils.trim(userID))) {
            resultDesc = resultDesc + "，用户账号为空！";
            logger.error(resultDesc);
            resp.setResultCode(ResultCode.PARAMETER_IS_NOT_LEGAL);
            resp.setResultDesc(resultDesc);
            return resp;
        }
    	
    	String tmpCountHql = "select count(o.id) as count from TVodTimeLog o where";
    	String wherejpql = " o.account=?";
    	Object[] queryParams;
    	if (!StringUtils.isEmpty(StringUtils.trim(stb))) {
    		wherejpql += " and o.stbType=?";
    		queryParams = new Object[] {userID, stb};
    	}else {
    		queryParams = new Object[] {userID};
    	}
    	int tmpIntCount = 0;
    	List<TVvodTimeLogInfo> infosList = new ArrayList<TVvodTimeLogInfo>();
    	resp.setTvLogInfos(infosList);
    	
		try {
			List<Map<String, Object>> tmpListMapCount = entityDao.getScrollDataByHql(tmpCountHql+wherejpql, queryParams, -1, -1);
            
            if (CollectionUtils.isNotEmpty(tmpListMapCount)) {
                Map<String, Object> tmpMapCount = tmpListMapCount.get(0);
                Long tmpLongCount = (Long) tmpMapCount.get("count");
                tmpIntCount = tmpLongCount.intValue();
            }
            resp.setRecordSize(tmpIntCount);
            if (tmpIntCount <= 0) {
                return resp;
            }
			
	    	List<TVodTimeLog> ll = entityDao.getScrollData(TVodTimeLog.class, firstIndex, maxResult, wherejpql, queryParams);
	    	
	    	if(CollectionUtils.isNotEmpty(ll)) {
		    	TVvodTimeLogInfo infov;
	    		Iterator<TVodTimeLog> ite = ll.iterator();
	    		while(ite.hasNext()) {
	    			TVodTimeLog ttlLog = ite.next();
	    			infov = new TVvodTimeLogInfo();
	    			infov.setCategoryCode(ttlLog.getCategoryCode());	    			
	    			infov.setCategoryName(ttlLog.getCategoryName());
	    			infov.setContentCode(ttlLog.getContentCode());
	    			infov.setContentName(ttlLog.getContentName());
	    			infov.setPageIdentity(ttlLog.getPageIdentity());
	    			infov.setPageName(ttlLog.getPageName());
	    			//infov.setPlayTime(ttlLog.getTimes());
	    			infov.setParentPageIdentity(ttlLog.getProvinceIdentity());
	    			infov.setProvinceName(ttlLog.getProvinceName());
	    			infov.setProvinceIdentity(ttlLog.getProvinceIdentity());
	    			//infov.setPlatformType(ttlLog.getPlatformType());
	    			infov.setStb(ttlLog.getStbType());
	    			//infov.setType(ttlLog.getType());
	    			infov.setUserID(ttlLog.getAccount());
	    			//infov.setCpId(ttlLog.getCpCode());
	    			
	    			if(ttlLog.getTimes()==null) {
	    				infov.setPlayTime("");
	    			}else {
	    				infov.setPlayTime(String.valueOf(ttlLog.getTimes()));
	    			}
	    			
	    			if(ttlLog.getPlatformType()==null) {
	    				infov.setPlatformType("");
	    			}else{
	    				infov.setPlatformType(String.valueOf(ttlLog.getPlatformType()));
	    			}
	    			
	    			if(ttlLog.getType()==null) {
	    				infov.setType("");
	    			}else {
	    				infov.setType(String.valueOf(ttlLog.getType()));
	    			}
	    			
	    			if(ttlLog.getCpCode()==null) {
	    				infov.setCpId("");
	    			}else {
	    				infov.setCpId(String.valueOf(ttlLog.getCpCode()));
	    			}
	    			
	    			infosList.add(infov);
		    	}
	    	}else {
	    		logger.info(resultDesc+"查询为空");
	    	}
	    	
		} catch (SQLException e) {
			logger.error(resultDesc+"异常", e);
            resp.setResultCode(ResultCode.APPLICATION_EXCEPTION);
            resp.setResultDesc(resultDesc+"异常");
		}
		
		return resp;
    }

	@Override
	public DateReportOrderLogListResp getOrderLogList(String stb, String userID, int firstIndex, int maxResult) {
		DateReportOrderLogListResp resp = new DateReportOrderLogListResp();
    	String resultDesc = String.format("用户[%s]获取订购记录日志列表,盒子型号[%s]", userID, stb);
    	
    	if (StringUtils.isEmpty(StringUtils.trim(userID))) {
            resultDesc = resultDesc + "，用户账号为空！";
            logger.error(resultDesc);
            resp.setResultCode(ResultCode.PARAMETER_IS_NOT_LEGAL);
            resp.setResultDesc(resultDesc);
            return resp;
        }
    	
    	String tmpCountHql = "select count(o.id) as count from TOrderLog o where";
    	String wherejpql = " o.account=?";
    	Object[] queryParams;
    	if (!StringUtils.isEmpty(StringUtils.trim(stb))) {
    		wherejpql += " and o.stbType=?";
    		queryParams = new Object[] {userID, stb};
    	}else {
    		queryParams = new Object[] {userID};
    	}
    	int tmpIntCount = 0;
    	List<TVorderLogInfo> infosList = new ArrayList<TVorderLogInfo>();
    	resp.setTvLogInfos(infosList);
		try {
			List<Map<String, Object>> tmpListMapCount = entityDao.getScrollDataByHql(tmpCountHql+wherejpql, queryParams, -1, -1);
            
            if (CollectionUtils.isNotEmpty(tmpListMapCount)) {
                Map<String, Object> tmpMapCount = tmpListMapCount.get(0);
                Long tmpLongCount = (Long) tmpMapCount.get("count");
                tmpIntCount = tmpLongCount.intValue();
            }
            resp.setRecordSize(tmpIntCount);
            if (tmpIntCount <= 0) {
                return resp;
            }
			
	    	List<TOrderLog> ll = entityDao.getScrollData(TOrderLog.class, firstIndex, maxResult, wherejpql, queryParams);
	    	
	    	if(CollectionUtils.isNotEmpty(ll)) {
		    	TVorderLogInfo infov;
	    		Iterator<TOrderLog> ite = ll.iterator();
	    		while(ite.hasNext()) {
	    			TOrderLog ttlLog = ite.next();
	    			infov = new TVorderLogInfo();
	    			infov.setCategoryCode(ttlLog.getCategoryCode());	    			
	    			infov.setCategoryName(ttlLog.getCategoryName());
	    			infov.setContentCode(ttlLog.getContentCode());
	    			infov.setContentName(ttlLog.getContentName());
	    			infov.setPageIdentity(ttlLog.getPageIdentity());
	    			infov.setPageName(ttlLog.getPageName());
	    			infov.setParentPageIdentity(ttlLog.getProvinceIdentity());
	    			infov.setProvinceName(ttlLog.getProvinceName());
	    			infov.setProvinceIdentity(ttlLog.getProvinceIdentity());
	    			infov.setStb(ttlLog.getStbType());
	    			infov.setUserID(ttlLog.getAccount());
	    			
	    			if(ttlLog.getAction()==null) {
	    				infov.setAction("");
	    			}else {
	    				infov.setAction(String.valueOf(ttlLog.getAction()));
	    			}
	    			
	    			if(ttlLog.getPlatformType()==null) {
	    				infov.setPlatformType("");
	    			}else{
	    				infov.setPlatformType(String.valueOf(ttlLog.getPlatformType()));
	    			}
	    			
	    			if(ttlLog.getType()==null) {
	    				infov.setType("");
	    			}else {
	    				infov.setType(String.valueOf(ttlLog.getType()));
	    			}
	    			
	    			if(ttlLog.getCpCode()==null) {
	    				infov.setCpId("");
	    			}else {
	    				infov.setCpId(String.valueOf(ttlLog.getCpCode()));
	    			}
	    			
	    			infosList.add(infov);
		    	}
	    	}else {
	    		logger.info(resultDesc+"查询为空");
	    	}
	    	
		} catch (SQLException e) {
			logger.error(resultDesc+"异常，", e);
            resp.setResultCode(ResultCode.APPLICATION_EXCEPTION);
            resp.setResultDesc(resultDesc+"异常");
		}
		
		return resp;
    }
	
	@Override
	public DateReportResp addSearchHisLog(String userID, String key, String code, String name, String pageNo, String poster, String operatorIdentity, String operatorName, String resolution) {
		DateReportResp resp = new DateReportResp();
		
		String areaIdentity = "";
		String areaName = "";
		try {
			Map<String, String> map = getAreaByUid(userID);
			areaIdentity = map.get("code");
			areaName = map.get("name");
		} catch (SQLException e1) {
			logger.error("", e1);
		}

        try {
			TSearchHistroy tsearchHistroy = null;
			
			//根据userID 和 内容code查找 记录 存在修改 不存在 新增     地区根据userID获取
			tsearchHistroy = entityDao.get(TSearchHistroy.class, "o.account=?1 and o.contentCode=?2", new Object[]{userID, code});
			if(tsearchHistroy==null){
				tsearchHistroy = new TSearchHistroy();
				tsearchHistroy.setCreateTime(new Date());
			}
			
	        tsearchHistroy.setAccount(userID);
	        tsearchHistroy.setSearchName(key);
	        tsearchHistroy.setContentCode(code);
	        tsearchHistroy.setContentName(name);
	        
	        tsearchHistroy.setOperatorIdentity(operatorIdentity);
	        tsearchHistroy.setOperatorName(operatorName);
	        tsearchHistroy.setAreaIdentity(areaIdentity);
	        tsearchHistroy.setAreaName(areaName);
	        
	        tsearchHistroy.setPoster(poster);
	        tsearchHistroy.setUpdateTime(new Date());
	        
	        if(StringUtils.isNotBlank(resolution)) {
	        	tsearchHistroy.setHdflag(Integer.valueOf(resolution));
	        }
	        
	        if(StringUtils.isNotBlank(pageNo)) {
	        	tsearchHistroy.setPageNo(Integer.valueOf(pageNo));
	        }
	        
	        entityDao.saveObj(tsearchHistroy);
	        logger.info("添加搜索历史成功");
        } catch (Exception e) {
            logger.error("添加搜索历史失败，系统异常，" + e.getMessage(), e);
            resp.setResultCode(ResultCode.APPLICATION_EXCEPTION);
            resp.setResultDesc("添加搜索历史失败，系统异常");
        }
        return resp;
	}

	@Override
	public DateReportSearchHisListResp getSearchHisList(String userID, int maxResult) {
		String resultDesc = String.format("用户[%s]获取搜索历史日志列表", userID);
		DateReportSearchHisListResp resp = new DateReportSearchHisListResp();
		
		if (StringUtils.isEmpty(StringUtils.trim(userID))) {
            resultDesc = resultDesc + "，用户账号为空！";
            logger.error(resultDesc);
            resp.setResultCode(ResultCode.PARAMETER_IS_NOT_LEGAL);
            resp.setResultDesc(resultDesc);
            return resp;
        }
		
		//String tmpCountHql = "select count(o.id) as count from TSearchHistroy o where";
    	String wherejpql = " o.account=?";
    	Object[] queryParams = new Object[] {userID};
    	
    	int tmpIntCount = 0;
    	List<TSearchHisLogInfo> infosList = new ArrayList<TSearchHisLogInfo>();
    	resp.setSearchInfos(infosList);
    	
    	try {
			//List<Map<String, Object>> tmpListMapCount = entityDao.getScrollDataByHql(tmpCountHql+wherejpql, queryParams, -1, -1);
            
            //if (CollectionUtils.isNotEmpty(tmpListMapCount)) {
            //    Map<String, Object> tmpMapCount = tmpListMapCount.get(0);
            //    Long tmpLongCount = (Long) tmpMapCount.get("count");
            //    tmpIntCount = tmpLongCount.intValue();
            //}
            
            if (maxResult < 0) {
                tmpIntCount = 10;
            }
            if (maxResult > 10) {
                tmpIntCount = 10;
            }
			
	    	LinkedHashMap<String, String> orderBy = new LinkedHashMap<String, String>();
			orderBy.put("updateTime", "desc");
			
			List<TSearchHistroy> ll = entityDao.getScrollData(TSearchHistroy.class, 0, tmpIntCount, wherejpql, queryParams, orderBy);
			tmpIntCount = ll.size();
	    	if(CollectionUtils.isNotEmpty(ll)) {
	    		tmpIntCount = ll.size();
	    		TSearchHisLogInfo infov;
	    		Iterator<TSearchHistroy> ite = ll.iterator();
	    		while(ite.hasNext()) {
	    			TSearchHistroy ttlLog = ite.next();
	    			infov = new TSearchHisLogInfo();
	    			infov.setContentCode(ttlLog.getContentCode());
	    			infov.setContentName(ttlLog.getContentName());
	    			infov.setUserID(ttlLog.getAccount());
	    			infov.setKey(ttlLog.getSearchName());
	    			infov.setPageNo(String.valueOf(ttlLog.getPageNo()));
	    			infov.setPoster(ttlLog.getPoster());
	    			
	    			infosList.add(infov);
		    	}
	    		resp.setRecordSize(tmpIntCount);
	    	}else {
	    		logger.info(resultDesc+"查询为空");
	    		resp.setRecordSize(0);
	    	}
	    	
		} catch (SQLException e) {
			logger.error(resultDesc+"异常", e);
            resp.setResultCode(ResultCode.APPLICATION_EXCEPTION);
            resp.setResultDesc(resultDesc+"异常");
		}
		
		return resp;
	}
}
